//
//  CinemaViewController.m
//  MyMovie
//
//  Created by lanou3g on 15/9/17.
//  Copyright (c) 2015年 HeQiangQiang. All rights reserved.
//

#import "CinemaViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "CinemaTableViewCell.h"
#import "Cinema.h"
#import "MapViewController.h"
#import "MJRefresh.h"

@interface CinemaViewController ()<UISearchBarDelegate,BMKLocationServiceDelegate>

//经度容器
@property (strong, nonatomic) NSString *longitudeLabel;
//纬度容器
@property (strong, nonatomic) NSString *latitoudeLabel;

@property (nonatomic, strong) UISearchBar *search;
@property (nonatomic, strong) UITextField *addressField;

@property (nonatomic, strong) NSMutableDictionary *provinceDic;
@property (nonatomic, strong) NSMutableArray *array;

//地理编码对象
//CLGeocoder 的字面意思是地标，封装详细的地址位置信息
@property (nonatomic, strong) CLGeocoder *geocoder;

@property (strong, nonatomic) BMKLocationService *locService;

@end

@implementation CinemaViewController

- (NSMutableDictionary *)provinceDic {
    if (!_provinceDic) {
        _provinceDic = [NSMutableDictionary dictionary];
    }
    return _provinceDic;
}

- (NSMutableArray *)array {
    if (!_array) {
        _array = [NSMutableArray array];
    }
    return _array;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    UIVisualEffectView *backVisual = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]];
    backVisual.frame = self.tableView.bounds;
    backVisual.alpha = 1.0;
    self.tableView.backgroundView = backVisual;
    
    __block CinemaViewController *cinema = self;
    [self.tableView addHeaderWithCallback:^{
        [cinema.tableView headerEndRefreshing];
    }];
    
    [SVProgressHUD show];
    [self.tableView registerClass:[CinemaTableViewCell class] forCellReuseIdentifier:@"Cell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.view.backgroundColor = [UIColor clearColor];
    
    UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"42"] style:(UIBarButtonItemStylePlain) target:self action:@selector(button)];
    self.navigationItem.rightBarButtonItem = button;

    [self setUp];
    
}
//获的附近位置
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation {
    self.latitoudeLabel = [NSString stringWithFormat:@"%f",_locService.userLocation.location.coordinate.latitude];
    self.longitudeLabel = [NSString stringWithFormat:@"%f",_locService.userLocation.location.coordinate.longitude];

    [self setUrl];
    NSLog(@"%f",_locService.userLocation.location.coordinate.latitude);
}


- (void)setUrl {
    [self.array removeAllObjects];
    NSString *string = [kCinemaUrl stringByReplacingOccurrencesOfString:@"经度" withString:self.latitoudeLabel];
    NSString * string1 = [string stringByReplacingOccurrencesOfString:@"纬度" withString:self.longitudeLabel];
    [LORequestManger GET:string1 success:^(id response) {
        NSDictionary *dic = (NSDictionary *)response;
        for (NSDictionary *pic in dic[@"entries"]) {
            Cinema *model = [Cinema shareJsonWithDic:pic];
            
            [self.array addObject:model];
        }
        [self.tableView reloadData];
        [SVProgressHUD dismiss];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.array.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CinemaTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    Cinema *model = self.array[indexPath.row];
    cell.label1.text = model.title;
    NSDictionary *dic = model.location;
    cell.label2.text = dic[@"address"];
    NSArray *arr = [NSArray arrayWithArray:model.phone];
    cell.label3.text = arr[0];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 120 * kFitHeight;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [_locService stopUserLocationService];
    MapViewController *view = [[MapViewController alloc] init];
    Cinema *model = self.array[indexPath.row];
    view.model = model;
    view.name = model.title;
    view.coordinate = [NSDictionary dictionaryWithDictionary:model.location[@"coordinate"]];
    [self.navigationController pushViewController:view animated:YES];
}
- (void)setUp {
    self.search = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 20, kWidth, 44)];
    self.search.placeholder = @"省份+城市";
    [self.search setShowsCancelButton:YES animated:YES];
    self.search.hidden = YES;
    self.search.delegate = self;
    [self.navigationController.view addSubview:self.search];
}
- (void)button {
    self.search.hidden = NO;
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [self.search resignFirstResponder];
    self.search.hidden = YES;
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [self.search resignFirstResponder];
    //获取用户输入的地址
    NSString *addressStr = self.search.text;
    //判断地址为空或者字符串的长度为0时
    if (addressStr == nil || addressStr.length == 0) {
        NSLog(@"请输入地址");
        return;
    }
    [self.geocoder geocodeAddressString:addressStr completionHandler:^(NSArray *placemarks, NSError *error) {
        //如果有错误信息，或者是数组中获取的地名元素数量为0，那么说明没有找到
        if (placemarks.count == 0 || error != nil) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"未找到地址" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alert show];
            return ;
        }
        // placemarks地标数组, 地标数组中存放着地标, 每一个地标包含了该位置的经纬度以及城市/区域/国家代码/邮编等等...
        //  取得第一个地标, 地标中存储了详细的地址信息, !!一个地名可能搜索出多个地址
        // 获取数组中的第一个地标
        CLPlacemark *placemark = [placemarks firstObject];
        //最后一个地标
        //CLPlacemark *placemark = [placemarks lastObject];
        //显示地区的经度
        self.latitoudeLabel = [NSString stringWithFormat:@"%f", placemark.location.coordinate.latitude];
        //显示地区的纬度
        self.longitudeLabel = [NSString stringWithFormat:@"%f", placemark.location.coordinate.longitude];
        [self setUrl];
    }];
    
}
- (void)viewWillAppear:(BOOL)animated {
    //设置定位精确度，默认：kCLLocationAccuracyBest
    [BMKLocationService setLocationDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
    //指定最小距离更新(米)，默认：kCLDistanceFilterNone
    [BMKLocationService setLocationDistanceFilter:100.f];
    
    //初始化BMKLocationService
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    //启动LocationService
    [_locService startUserLocationService];
}
//懒加载
- (CLGeocoder *)geocoder {
    if (!_geocoder) {
        _geocoder = [[CLGeocoder alloc] init];
    }
    return _geocoder;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
